<div id="navbar">
    <header>
        <div class="logo">闪购</div>
        <div class="nav">
            <a href="index.html">首页</a>
            <a href="cart.html">购物车 <span id="cartCount">0</span></a>
            <span class="welcome">欢迎, <span id="username">游客</span></span>
            <span class="logout" onclick="logout()">退出登录</span>
        </div>
    </header>
</div>

<script>
    // 导航栏共用脚本
    function initNav() {
        // 显示用户名
        const usernameSpan = document.getElementById('username');
        const storedUsername = localStorage.getItem('username');
        usernameSpan.textContent = storedUsername || '游客';

        // 更新购物车数量
        updateCartCount();
    }

    // 退出登录
    function logout() {
        localStorage.removeItem('username');
        window.location.href = 'login.html';
    }

    // 更新购物车数量显示
    function updateCartCount() {
        const username = localStorage.getItem('username');
        if (!username) {
            document.getElementById('cartCount').textContent = '0';
            return;
        }

        // 从全局购物车数据中获取当前用户的购物车
        const allCarts = JSON.parse(localStorage.getItem('allCarts') || '{}');
        const userCart = allCarts[username] || [];
        const totalCount = userCart.reduce((sum, item) => sum + (item.quantity || 1), 0);

        document.getElementById('cartCount').textContent = totalCount;
    }

    // 初始化导航
    initNav();
</script>